const api = require('../../api/api');
const app = getApp();
Page({
  data: {
    type: '',
    id: '',
    film: {},
    start: 0,
    count: 10,
    total: 0,
    comments: [],
    showNomore: false, //是否显示没有更多
    showLoading: false, //是否显示loading
    addFavorite: true, //控制显示收藏
  },

  onLoad: function (options) {
    this.data.type = options.type;
    this.data.id = options.id;
    if (this.data.total == 0) {
      this.setData({
        showLoading: false
      })
    }
  },

  onReady: function () {
    this.loadDetailData();
  },
  loadDetailData() {
    // 获取电影详情
    api.loadFilmByFilmId({
      type: this.data.type,
      id: this.data.id,
    }).then(data => {

      this.setData({
        film: data,
      })
    })
    // 获取电影评论
    this.loadComment();

  },
  loadComment() {
    return api.loadCommentsByFilmId({
        type: this.data.type,
        id: this.data.id,
        start: this.data.start,
        count: this.data.count,
        order_by: 'time'
      })
      .then(data => {
        this.setData({
          comments: this.data.comments.concat(data.interests), //评论累加
          total: data.toal, //总条数
          start: this.data.start + this.data.count, //起始索引累加
        })

      })

  },
  showMore() {
    if (this.data.start > this.data.total || this.data.total < this.data.count) {
      return this.setData({
        showNomore: true
      })
    }
    this.loadComment()
  },
  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.start > this.data.total) {
      return this.setData({
        showNomore: true
      })
    }
  },
  // 添加收藏
  addFavorite() {
    // 判断是否已授权登录
    if (!app.userInfo) {
      return wx.showToast({
        title: '请先登录',
        image: '/imgs/error.png',
        duration: 2000,
        success() {
          setTimeout(() => {
            // 使用计时器实现延迟
            wx: wx.switchTab({
              url: '/pages/about/about',
            })
          }, 2000)
        }
      })
    }
    // 获取本地 缓存中的收藏数据
    let favorites = wx.getStorageSync('favorites') || {}; //第一次收藏时值为空字符串

    if (favorites[this.data.id]) {
      return wx.showToast({
        title: '已收藏',
        image: '/imgs/error.png',
      })
    }

    // 由于datail中的film对象和home中的film对象属性有差异，需要手动调整
    this.data.film.cover.url = this.data.film.pic.normal
    // 添加电影到本地缓存中
    favorites[this.data.id] = this.data.film;
    wx.setStorageSync('favorites', favorites)
    wx.showToast({
      title: '收藏成功',
      image: '/imgs/success.png'
    })
    this.setData({
      addFavorite: !this.data.addFavorite,
    })

  },
  onShow() {
    // 判断电影是否收藏
    let favorites = wx.getStorageSync('favorites')
    if (favorites[this.data.id]) {
      this.setData({
        addFavorite: false,
      })
    }
    if (this.data.total == 0) {
      this.setData({
        showLoading: false
      })
    }
  },
})